package com.neusoft.elm.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.neusoft.elm.dao.OrderDetailetDao;
import com.neusoft.elm.po.Food;
import com.neusoft.elm.po.OrderDetailet;
import com.neusoft.elm.util.DBUtil;

/**
 * 订单明细数据访问层实现类
 */
public class OrderDetailetDaoImpl implements OrderDetailetDao {
    private Connection con = null;
    private PreparedStatement pst = null;
    private ResultSet rs = null;

    @Override
    public int saveOrderDetailetBatch(List<OrderDetailet> list) throws Exception {
        int result = 0;
        // 更新SQL语句，包含商品快照字段
        StringBuffer stringBuffer = new StringBuffer("insert into orderdetailet(orderId,foodId,quantity,foodName,foodPrice,foodExplain) values");
        for (OrderDetailet od : list) {
            stringBuffer.append("(")
                .append(od.getOrderId()).append(",")
                .append(od.getFoodId()).append(",")
                .append(od.getQuantity()).append(",")
                .append("'").append(od.getFoodName() != null ? od.getFoodName().replace("'", "''") : "").append("',")
                .append(od.getFoodPrice() != null ? od.getFoodPrice() : "null").append(",")
                .append("'").append(od.getFoodExplain() != null ? od.getFoodExplain().replace("'", "''") : "").append("'")
                .append("),");
        }
        // 去掉SQL语句中的最后一个逗号
        String sql = stringBuffer.toString().substring(0, stringBuffer.toString().length() - 1);
        System.out.println("批量插入订单明细SQL（含快照数据）: " + sql);
        try {
            con = DBUtil.getConnection();
            pst = con.prepareStatement(sql);
            result = pst.executeUpdate();
            System.out.println("批量插入订单明细成功，影响行数: " + result);
        } finally {
            DBUtil.close(pst);
        }
        return result;
    }

    @Override
    public List<OrderDetailet> listOrderDetailetByOrderId(Integer orderId) throws Exception {
        List<OrderDetailet> list = new ArrayList<>();
        StringBuffer sql = new StringBuffer();
        // 优先使用快照数据，如果快照数据为空则关联查询实时数据（兼容历史数据）
        sql.append(" select o.*, ");
        sql.append("        COALESCE(o.foodName, f.foodName) as displayFoodName, ");
        sql.append("        COALESCE(o.foodPrice, f.foodPrice) as displayFoodPrice, ");
        sql.append("        COALESCE(o.foodExplain, f.foodExplain) as displayFoodExplain, ");
        sql.append("        f.foodId ffoodId ");
        sql.append(" from orderdetailet o left join food f on o.foodId=f.foodId ");
        sql.append(" where o.orderId=? ");
        try {
            con = DBUtil.getConnection();
            pst = con.prepareStatement(sql.toString());
            pst.setInt(1, orderId);
            rs = pst.executeQuery();
            while (rs.next()) {
                OrderDetailet od = new OrderDetailet();
                od.setOdId(rs.getInt("odId"));
                od.setOrderId(rs.getInt("orderId"));
                od.setFoodId(rs.getInt("foodId"));
                od.setQuantity(rs.getInt("quantity"));
                
                // 设置快照字段（如果存在）
                od.setFoodName(rs.getString("foodName"));
                od.setFoodPrice(rs.getDouble("foodPrice"));
                od.setFoodExplain(rs.getString("foodExplain"));
                
                // 设置关联的食品信息，优先使用快照数据
                Food food = new Food();
                food.setFoodId(rs.getInt("ffoodId"));
                food.setFoodName(rs.getString("displayFoodName"));
                food.setFoodPrice(rs.getDouble("displayFoodPrice"));
                food.setFoodExplain(rs.getString("displayFoodExplain"));
                od.setFood(food);
                
                list.add(od);
            }
        } finally {
            DBUtil.close(rs, pst);
        }
        return list;
    }
}